package com.maila.xiaoaoschool.fragment;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.transition.TransitionSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.maila.xiaoaoschool.R;
import com.maila.xiaoaoschool.activity.AllFoodsActivity;
import com.maila.xiaoaoschool.activity.ExpressActivity;
import com.maila.xiaoaoschool.activity.SearchActivity;
import com.maila.xiaoaoschool.activity.SearchShopActivity;
import com.maila.xiaoaoschool.adapter.MainLocationAdapter;
import com.maila.xiaoaoschool.adapter.MainUAdapter;
import com.maila.xiaoaoschool.api.IndexApi;
import com.maila.xiaoaoschool.entity.IndexCarouselFigure;
import com.maila.xiaoaoschool.entity.IndexOrderData;
import com.maila.xiaoaoschool.entity.IndexRecommendShop;
import com.maila.xiaoaoschool.entity.News;
import com.maila.xiaoaoschool.image.NetworkImageHolderView;
import com.maila.xiaoaoschool.net.VolleyInterface;
import com.maila.xiaoaoschool.util.NullPointUtils;
import com.maila.xiaoaoschool.util.StartActivityUtils;
import com.maila.xiaoaoschool.widget.NoScrollGridView;
import com.maila.xiaoaoschool.widget.NoScrollListView;
import com.maila.xiaoaoschool.widget.UPMarqueeView;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by Administrator on 2017/9/23.
 */

public class LocationFragment extends Fragment implements NetworkImageHolderView.BannerCallback {


    Unbinder unbinder;
    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.all_meishi)
    AutoLinearLayout allMeishi;
    @BindView(R.id.all_chaoshi)
    AutoLinearLayout allChaoshi;
    @BindView(R.id.all_kuaidi)
    AutoLinearLayout allKuaidi;
    @BindView(R.id.all_ziying)
    AutoLinearLayout allZiying;
    @BindView(R.id.laba)
    ImageView laba;
    @BindView(R.id.upview1)
    UPMarqueeView upview1;
    @BindView(R.id.gv_youxuan)
    NoScrollGridView gvYouxuan;
    @BindView(R.id.rb_zh)
    RadioButton rbZh;
    @BindView(R.id.rb_xl)
    RadioButton rbXl;
    @BindView(R.id.rb_jl)
    RadioButton rbJl;
    @BindView(R.id.lv_fujin)
    NoScrollListView lvFujin;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.hot_refresh)
    MaterialRefreshLayout hotRefresh;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_location)
    AutoLinearLayout llLocation;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_search)
    AutoLinearLayout mSearchLayout;
    @BindView(R.id.toolbar)
    AutoRelativeLayout toolbar;
    @BindView(R.id.rl_order_status)
    AutoRelativeLayout RlOrderStatus;

    private TransitionSet mSet;
    boolean isExpand = false;
    MainLocationAdapter locationAdapter;
    MainUAdapter mainUAdapter;
    Gson gson = new Gson();
    NetworkImageHolderView.BannerCallback callback;
    private String lat = "36.71287";
    private String lng = "119.126626";
    private String adcode = "1";
    private int page = 1;
    private int size = 6;
    private String field = "evaluate";
    private List<View> views=new ArrayList<>();

    public static LocationFragment newInstance(String param1) {
        LocationFragment fragment = new LocationFragment();
        Bundle args = new Bundle();
        args.putString("agrs1", param1);
        fragment.setArguments(args);
        return fragment;
    }

    public LocationFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_location, container, false);
        unbinder = ButterKnife.bind(this, view);
        callback = this;
        locationAdapter = new MainLocationAdapter(this.getActivity());
        mainUAdapter = new MainUAdapter(this.getActivity());
        gvYouxuan.setAdapter(mainUAdapter);
        lvFujin.setAdapter(locationAdapter);
        hotRefresh.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                hotRefresh.finishRefresh();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                initlocationshop();
            }
        });
//        //设置toolbar初始透明度为0
//        toolbar.getBackground().mutate().setAlpha(0);
        //scrollview滚动状态监听
//        scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
//            @Override
//            public void onScrollChanged() {
//                //改变toolbar的透明度
////                changeToolbarAlpha();
//                //滚动距离>=大图高度-toolbar高度 即toolbar完全盖住大图的时候 且不是伸展状态 进行伸展操作
////                if (scrollView.getScrollY() >= convenientBanner.getHeight() - toolbar.getHeight() && !isExpand) {
//////                    expand();
////                    isExpand = true;
////                }
//                //滚动距离<=0时 即滚动到顶部时  且当前伸展状态 进行收缩操作
////                else if (scrollView.getScrollY() <= 0 && isExpand) {
//////                    reduce();
////                    isExpand = false;
////                }
//            }
//        });
        AutoUtils.autoSize(view);
        initdata();
        requestViewFoucus(convenientBanner);
        return view;
    }

    /**
     * 初始化首页 界面数据
     */
    private void initdata() {
        initindexcarousel();
        initrecommendshop();
        initlocationshop();
    }

    @Override
    public void onResume() {
        super.onResume();
        checkorderstatus();
        initdata();
    }

    private void checkorderstatus() {
        new  IndexApi(getActivity(), new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                IndexOrderData data=gson.fromJson(result,IndexOrderData.class);
                if(data.getResult()==1&&data.getData()!=null&&data.getData().size()>0){
                    RlOrderStatus.setVisibility(View.VISIBLE);
                    initviews(data.getData());
                }else {
                    RlOrderStatus.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).get_index_order_list(1,6);
    }


    private void initviews(final List<IndexOrderData.DataBean> data) {
        for (int i = 0; i < data.size(); i++) {
            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.item_view, null);
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.tv1);

            final int finalI = i;
            moreView.findViewById(R.id.tv1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });

            String hint ="";
            switch (data.get(i).getType()){
                case 1:
                    switch (data.get(i).getStatus()){
                        case 0:
                            hint="我要取件"+data.get(i).getShopname()+"待接单";
                            break;
                        case 1:
                            hint="我要取件"+data.get(i).getShopname()+"未支付";
                            break;
                        case 2:
                            hint="我要取件"+data.get(i).getShopname()+"待取件";
                            break;
                        case 3:
                            hint="我要取件"+data.get(i).getShopname()+"待评价";
                            break;
                    }
                    break;
                case 2:
                    switch (data.get(i).getStatus()){
                        case 0:
                             hint="我要发件"+data.get(i).getShopname()+"待接单";
                            break;
                        case 1:
                            hint="我要发件"+data.get(i).getShopname()+"待反馈";
                            break;
                        case 2:
                            hint="我要发件"+data.get(i).getShopname()+"待支付";
                            break;
                        case 3:
                            hint="我要发件"+data.get(i).getShopname()+"待评价";
                            break;
                    }
                    break;
                case 3:
                    switch (data.get(i).getStatus()){
                        case 0:
                            hint="我的外卖"+data.get(i).getShopname()+"待接单";
                            break;
                        case 1:
                            hint="我的外卖"+data.get(i).getShopname()+"商家已接单";
                            break;
                        case 2:
                            hint="我的外卖"+data.get(i).getShopname()+"配送小哥到店中";
                            break;
                        case 3:
                            hint="我的外卖"+data.get(i).getShopname()+"配送中";
                            break;
                        case 4:
                            hint="我的外卖"+data.get(i).getShopname()+"待评价";
                            break;
                    }
                    break;
            }
                tv1.setText(hint);

            //添加到循环滚动数组里面去
            views.add(moreView);
        }
        upview1.setViews(views);
    }
    /**
     * 获取 附近商家列表
     */
    private void initlocationshop() {
        new IndexApi(getActivity(), new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                try {
                    IndexRecommendShop recommendShop = gson.fromJson(result, IndexRecommendShop.class);
                    if (recommendShop.getResult() == 1) {
                        if (page == 1) {
                            locationAdapter.setMdata(recommendShop.getData());
                        } else {
                            locationAdapter.addMdata(recommendShop.getData());
                        }
                        hotRefresh.finishRefreshLoadMore();
                        ++page;

                    } else {
                        hotRefresh.finishRefreshLoadMore();
                        hotRefresh.setLoadMore(false);
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).getIndexShop(lat, lng, page, size, field, "desc", adcode);
    }

    /**
     * 获取 为你优选
     */
    private void initrecommendshop() {
        new IndexApi(getActivity(), new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                try {
                    IndexRecommendShop recommendShop = gson.fromJson(result, IndexRecommendShop.class);
                    if (recommendShop.getResult() == 1) {
                        mainUAdapter.setMdata(recommendShop.getData());
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).getRecommendShop(lat, lng, 1, 3, "evaluate", "desc", adcode);
    }

    /**
     * 初始化轮播图
     */
    private void initindexcarousel() {
        new IndexApi(getActivity(), new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                IndexCarouselFigure carousel = gson.fromJson(result, IndexCarouselFigure.class);
                if (carousel.getResult() == 1) {

                    convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                        @Override
                        public NetworkImageHolderView createHolder() {
                            return new NetworkImageHolderView(callback);
                        }
                    }, carousel.getData())
                            .setPageIndicator(new int[]{R.mipmap.lunboa, R.mipmap.lunbob})
                            .setPointViewVisible(true)
                            //设置自动切换（同时设置了切换时间间隔）
                            .startTurning(3000)
                            //设置指示器的方向（左、中、右）
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);


                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).getIndexCarouselFigure();
    }

    private void changeToolbarAlpha() {
        int scrollY = scrollView.getScrollY();
        //快速下拉会引起瞬间scrollY<0
        if (scrollY < 0) {
//            toolbar.getBackground().mutate().setAlpha(0);
            return;
        }
//        //计算当前透明度比率
//        float radio = Math.min(1, scrollY / (convenientBanner.getHeight() - toolbar.getHeight() * 1f));
        //设置透明度
//        toolbar.getBackground().mutate().setAlpha((int) (radio * 0xFF));
    }

    private void requestViewFoucus(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }

    private void expand() {
        //设置伸展状态时的布局
        tvSearch.setText("搜索简书的内容和朋友");
        RelativeLayout.LayoutParams LayoutParams = (RelativeLayout.LayoutParams) mSearchLayout.getLayoutParams();
        LayoutParams.width = LayoutParams.MATCH_PARENT;
        LayoutParams.setMargins(dip2px(10), dip2px(10), dip2px(10), dip2px(10));
        mSearchLayout.setLayoutParams(LayoutParams);
        //开始动画
        beginDelayedTransition(mSearchLayout);
    }

    private void reduce() {
        //设置收缩状态时的布局
        tvSearch.setText("搜索");
        RelativeLayout.LayoutParams LayoutParams = (RelativeLayout.LayoutParams) mSearchLayout.getLayoutParams();
        LayoutParams.width = dip2px(80);
        LayoutParams.setMargins(dip2px(10), dip2px(10), dip2px(10), dip2px(10));
        mSearchLayout.setLayoutParams(LayoutParams);
        //开始动画
        beginDelayedTransition(mSearchLayout);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    void beginDelayedTransition(ViewGroup view) {
        mSet = new AutoTransition();
        mSet.setDuration(300);
        TransitionManager.beginDelayedTransition(view, mSet);
    }

    private int dip2px(float dpVale) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpVale * scale + 0.5f);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.all_meishi, R.id.all_chaoshi, R.id.all_kuaidi, R.id.all_ziying, R.id.upview1, R.id.rb_zh, R.id.rb_xl, R.id.rb_jl, R.id.ll_location, R.id.ll_search,R.id.btn_new_user, R.id.btn_xianshi, R.id.btn_tejia, R.id.btn_manjian, R.id.btn_fanquan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_meishi:
                StartActivityUtils.start(getActivity(), AllFoodsActivity.class);
                break;
            case R.id.all_chaoshi:
                StartActivityUtils.startByOpt(getActivity(), SearchShopActivity.class, 2, "");
                break;
            case R.id.all_kuaidi:
                StartActivityUtils.start(getActivity(), ExpressActivity.class);
                break;
            case R.id.all_ziying:
                StartActivityUtils.startByOpt(getActivity(), SearchShopActivity.class, 3, "");
                break;
            case R.id.upview1:
                break;
            case R.id.rb_zh:
                reset_rb();
                rbZh.setChecked(true);
                field = "evaluate";
                page = 1;
                initlocationshop();
                break;
            case R.id.rb_xl:
                reset_rb();
                rbXl.setChecked(true);
                field = "sellcount";
                page = 1;
                initlocationshop();
                break;
            case R.id.rb_jl:
                reset_rb();
                rbJl.setChecked(true);
                field = "range";
                page = 1;
                initlocationshop();
                break;
            case R.id.ll_location:
                break;
            case R.id.ll_search:
                StartActivityUtils.start(getActivity(), SearchActivity.class);
                break;
            case R.id.btn_new_user:
                break;
            case R.id.btn_xianshi:
                break;
            case R.id.btn_tejia:
                break;
            case R.id.btn_manjian:
                break;
            case R.id.btn_fanquan:
                break;
        }
    }

    private void reset_rb() {
        rbJl.setChecked(false);
        rbXl.setChecked(false);
        rbZh.setChecked(false);
    }

    @Override
    public void click(int position) {

    }
}